<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">{{ id ? '编辑商品' : '新增商品' }}</text>
    </view>

    <!-- 商品表单 -->
    <uni-forms ref="form" :model="formData" :rules="rules" label-position="top">
      <!-- 商品名称 -->
      <uni-forms-item label="商品名称" name="name" required>
        <uni-easyinput v-model="formData.name" placeholder="请输入商品名称" />
      </uni-forms-item>

      <!-- 商品价格 -->
      <uni-forms-item label="商品价格（元）" name="price" required>
        <uni-easyinput type="digit" v-model="formData.price" placeholder="请输入商品价格" />
      </uni-forms-item>

      <!-- 打包费 -->
      <uni-forms-item label="打包费（元）" name="packagingFee" required>
        <uni-easyinput type="digit" v-model="formData.packagingFee" placeholder="请输入打包费" />
      </uni-forms-item>

      <!-- 商品分类 -->
      <uni-forms-item label="商品分类" name="categoryId" required>
        <uni-data-select v-model="formData.categoryId" :localdata="categories" />
      </uni-forms-item>

      <!-- 商品图片 -->
      <uni-forms-item label="商品图片" name="image" required>
        <uni-file-picker v-model="formData.image" file-mediatype="image" limit="1" @select="handleImageSelect" :auto-upload="false" />
      </uni-forms-item>

      <!-- 商品描述 -->
      <uni-forms-item label="商品描述" name="description">
        <uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入商品描述" />
      </uni-forms-item>

      <!-- 商品状态 -->
      <uni-forms-item label="商品状态" name="status">
        <switch :checked="formData.status === 1" @change="toggleStatus" color="#FF7F50" />
        <text class="status-text">{{ formData.status === 1 ? '上架中' : '已下架' }}</text>
      </uni-forms-item>

      <!-- 商品规格（动态增删组和选项） -->
      <view class="spec-section">
        <view class="spec-header">
          <text class="spec-title">商品规格</text>
          <button class="add-group-btn" @click="addSpecGroup">+ 添加规格组</button>
        </view>
        <view v-for="(group, groupIdx) in specGroups" :key="groupIdx" class="spec-group-card">
          <view class="spec-group-header">
            <view class="spec-group-label">规格组名称</view>
            <uni-easyinput v-model="group.name" placeholder="如颜色、尺寸" class="spec-group-input" />
            <button class="del-group-btn" @click="removeSpecGroup(groupIdx)">删除组</button>
          </view>
          <view class="spec-options">
            <view v-for="(option, optIdx) in group.options" :key="optIdx" class="spec-option-row">
              <view class="spec-option-label">选项名称</view>
              <uni-easyinput v-model="option.name" placeholder="如红色、L" class="spec-option-input" />
              <view class="spec-option-label">加价(元)</view>
              <uni-easyinput v-model.number="option.price" type="digit" placeholder="" class="spec-option-price" />
              <button class="del-option-btn" @click="removeSpecOption(groupIdx, optIdx)" v-if="group.options.length > 1">删除</button>
            </view>
            <button class="add-option-btn" @click="addSpecOption(groupIdx)">+ 添加选项</button>
          </view>
        </view>
      </view>
    </uni-forms>

    <!-- 底部操作按钮 -->
    <view class="footer">
      <button class="cancel-btn" @click="handleCancel">取消</button>
      <button class="submit-btn" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {getMerchantId} from '@/utils/merchant.js';
import { getGoodsCategories} from '@/api/goodsCategory';
import { getGoodsDetail, saveGoods, updateGoods } from '@/api/goods';
import { uploadToOSS, fetchAndScheduleStsToken, clearStsTokenTimer } from '@/utils/oss';

const form = ref(null);
const id = ref('');
const formData = ref({
  name: '',
  price: '',
  packagingFee: '',
  categoryId: '',
  image: [],
  description: '',
  status: 1,
  merchantId: getMerchantId()
});

const categories = ref([{ text: '请选择分类', value: '' }]);

const rules = {
  name: {
    rules: [{ required: true, errorMessage: '请输入商品名称' }]
  },
  price: {
    rules: [
      { required: true, errorMessage: '请输入商品价格' },
      { 
        validateFunction: function(rule, value, data, callback) {
          if (value && !/^\d+(\.\d{1,2})?$/.test(value)) {
            callback('价格格式不正确，请输入正数（最多保留2位小数）');
          }
          return true;
        }
      }
    ]
  },
  packagingFee: {
    rules: [
      { required: true, errorMessage: '请输入打包费' },
      { 
        validateFunction: function(rule, value, data, callback) {
          if (value && !/^\d+(\.\d{1,2})?$/.test(value)) {
            callback('打包费格式不正确，请输入正数（最多保留2位小数）');
          }
          return true;
        }
      }
    ]
  },
  categoryId: {
    rules: [{ required: true, errorMessage: '请选择商品分类' }]
  }
};

const toggleStatus = () => {
  formData.value.status = formData.value.status === 1 ? 0 : 1;
};

const handleCancel = () => {
  uni.navigateBack();
};

const specGroups = ref([]);

const addSpecGroup = () => {
  specGroups.value.push({ name: '', options: [{ name: '', price: 0 }] });
};
const removeSpecGroup = (idx) => {
  specGroups.value.splice(idx, 1);
};
const addSpecOption = (groupIdx) => {
  specGroups.value[groupIdx].options.push({ name: '', price: 0 });
};
const removeSpecOption = (groupIdx, optIdx) => {
  if (specGroups.value[groupIdx].options.length > 1) specGroups.value[groupIdx].options.splice(optIdx, 1);
};

const handleSubmit = async () => {
  try {
    await form.value.validate();
    // 规格组校验
    if (specGroups.value.length > 0) {
      for (let i = 0; i < specGroups.value.length; i++) {
        const group = specGroups.value[i];
        if (!group.name || group.name.trim() === "") {
          uni.showToast({ title: `请填写第${i + 1}个规格组名称`, icon: 'none' });
          return;
        }
        if (!Array.isArray(group.options) || group.options.length === 0) {
          uni.showToast({ title: `请为第${i + 1}个规格组添加至少一个选项`, icon: 'none' });
          return;
        }
        for (let j = 0; j < group.options.length; j++) {
          const option = group.options[j];
          if (!option.name || option.name.trim() === "") {
            uni.showToast({ title: `请填写第${i + 1}组第${j + 1}个选项名称`, icon: 'none' });
            return;
          }
        }
      }
    }
    let submitData = { ...formData.value };
    // 若image为数组，取第一个元素作为提交参数
    if (Array.isArray(submitData.image)) {
      submitData.image = submitData.image[0].url || '';
    }
    // 规格组序列化
    submitData.specJson = JSON.stringify(specGroups.value);
    let res;
    if (id.value) {
      res = await updateGoods({ ...submitData, id: id.value });
    } else {
      res = await saveGoods(submitData);
    }
    uni.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (e) {
    console.error('保存商品失败:', e);
  }
};

const loadCategories = async () => {
  const res = await getGoodsCategories(getMerchantId());
  if (res && res.data) {
    categories.value = [{ text: '请选择分类', value: '' }, ...res.data.map(item => ({ text: item.name, value: item.id }))];
  }
};

onLoad(async (options) => {
  await loadCategories();
  if (options.id) {
    id.value = options.id;
    const res = await getGoodsDetail(options.id);
    if (res && res.data) {
      formData.value = { ...res.data };
      formData.value.status = Number(formData.value.status);
      if (formData.value.image && typeof formData.value.image === 'string') {
        formData.value.image = [{ url: formData.value.image }];
      } else if (!formData.value.image) {
        formData.value.image = [];
      }
      // 反序列化规格组
      if (res.data.specJson) {
        try {
          specGroups.value = JSON.parse(res.data.specJson);
        } catch (e) {
          specGroups.value = [{ name: '', options: [{ name: '', price: 0 }] }];
        }
      }
    }
  }
});
onMounted(() => {
  fetchAndScheduleStsToken();
});
onUnmounted(() => {
  clearStsTokenTimer();
});

const handleImageSelect = async (e) => {
  try {
    const fileObj = e.tempFiles[0];
    if (!fileObj) return;
    console.log('图片选择对象:', fileObj); // 调试用，建议上线前移除
    uni.showLoading({ title: '上传中...' });
    // 兼容不同平台，优先使用path字段
    const filePath = fileObj.path || fileObj.url || '';
    if (!filePath) {
      uni.showToast({ title: '未获取到图片路径', icon: 'none' });
      return;
    }
    const ossUrl = await uploadToOSS(filePath, 'image');
    formData.value.image = [{ url: ossUrl }];
    console.log('上传成功，OSS地址:', ossUrl); // 调试用，建议上线前移除
    uni.showToast({ title: '上传成功', icon: 'success' });
  } catch (err) {
    uni.showToast({ title: '上传失败', icon: 'none' });
    console.error('图片上传失败:', err);
  } finally {
    uni.hideLoading();
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  padding-bottom: 120rpx; /* 为底部固定按钮预留空间 */
}

.header {
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.status-text {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  z-index: 999; /* 确保按钮在最上层 */
}

.cancel-btn {
  flex: 1;
  margin-right: 20rpx;
  background: #f7f7f7;
  color: #666;
}

.submit-btn {
  flex: 1;
  background: #FF7F50;
  color: #fff;
}
.spec-section {
  margin: 40rpx 0 0 0;
  background: #f9f9f9;
  border-radius: 16rpx;
  padding: 24rpx;
}
.spec-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16rpx;
}
.spec-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}
.add-group-btn {
  background: #FF7F50;
  color: #fff;
  border-radius: 8rpx;
  padding: 8rpx 24rpx;
  font-size: 26rpx;
}
.spec-group-card {
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  margin-bottom: 24rpx;
  padding: 20rpx;
}
.spec-group-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}
.spec-group-input {
  flex: 1;
  margin-right: 16rpx;
}
.del-group-btn {
  background: #f56c6c;
  color: #fff;
  border-radius: 8rpx;
  padding: 8rpx 20rpx;
  font-size: 24rpx;
}
.spec-options {
  margin-left: 0;
  /* 移除原有的 padding-bottom: 100rpx; 因为容器已经有了底部内边距 */
}
.spec-option-row {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}
.spec-option-input {
  flex: 2;
  margin-right: 12rpx;
}
.spec-option-price {
  flex: 1;
  margin-right: 12rpx;
}
.del-option-btn {
  background: #f56c6c;
  color: #fff;
  border-radius: 8rpx;
  padding: 6rpx 16rpx;
  font-size: 22rpx;
}
.add-option-btn {
  background: #67c23a;
  color: #fff;
  border-radius: 8rpx;
  padding: 8rpx 20rpx;
  font-size: 24rpx;
  margin-top: 8rpx;
}
</style>